<template>
  <lay-container fluid="true" class="user-box">
    <lay-card>
      <lay-form style="margin-top: 10px" :model="searchQuery" ref="queryRef">
        <lay-row>
          <lay-col :md="5">
            <lay-form-item label="用户名" label-width="80" prop="username">
              <lay-input v-model="searchQuery.username" placeholder="请输入" :allow-clear="true" style="width: 98%">
              </lay-input>
            </lay-form-item>
          </lay-col>
          <lay-col :md="5">
            <lay-form-item label="昵称" label-width="80" prop="nickName">
              <lay-input v-model="searchQuery.nickName" placeholder="请输入" :allow-clear="true" style="width: 98%">
              </lay-input>
            </lay-form-item>
          </lay-col>
          <lay-col :md="5">
            <lay-form-item label="状态" label-width="80" prop="status">
              <lay-select class="search-input" v-model="searchQuery.status" :allow-clear="true" placeholder="请选择">
                <lay-select-option value="on" label="启用"></lay-select-option>
                <lay-select-option value="off" label="禁用"></lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="5">
            <lay-form-item label-width="20">
              <lay-button style="margin-left: 20px" type="primary" @click="userPage()"> 查询 </lay-button>
              <lay-button @click="toReset(queryRef,userPage)"> 重置 </lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>
    <!-- table -->
    <div class="table-box">
      <lay-table
        :page="fxwPage.page"
        :height="'100%'"
        :columns="columns"
        :loading="fxwPage.loading.value"
        :default-toolbar="true"
        :data-source="fxwPage.dataSource.value"
        v-model:selected-keys="fxwPage.selectedKeys.value"
        @change="userPage">

        <template v-slot:toolbar>
          <lay-button v-perm="'user_add'" size="sm" type="primary" @click="toAddUserDom">
            <lay-icon class="layui-icon-addition"></lay-icon>
            新增
          </lay-button>
        </template>

        <!-- 列插槽-start -->
        <template v-slot:status="{ row }">
          <lay-switch v-model="row.status.code"
                      onswitch-value="on" unswitch-value="off"
                      onswitch-text="启用"  unswitch-text="禁用"
                      @change="status =>changeStatus(row,status)">
          </lay-switch>
        </template>
        <template v-slot:role="{ row }">
          <lay-tag size="sm" v-for="userRole in row.userRoleVOList">{{userRole.roleName}}</lay-tag>
        </template>

        <template v-slot:_index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <!-- 列插槽-end -->

        <template v-slot:operator="{ row }">
          <lay-dropdown size="sm" updateAtScroll>
            <lay-button type="primary">操作</lay-button>
            <template #content>
              <lay-dropdown-menu>
                <lay-dropdown-menu-item v-perm="'user_edit'" @click="toEditUserDom(row.id)">编辑</lay-dropdown-menu-item>
                <lay-dropdown-menu-item v-perm="'user_detail'" @click="toDetailUserDom(row.id)">详情</lay-dropdown-menu-item>
                <lay-dropdown-menu-item v-perm="'user_resetPassword'" @click="toResetPasswordDom(row)">改密</lay-dropdown-menu-item>
                <lay-dropdown-menu-item v-perm="'user_viewPassword'" @click="toViewPasswordDom(row)">解密</lay-dropdown-menu-item>
                <lay-dropdown-menu-item v-perm="'user_simulateLogin'" @click="toSimulateLoginDom(row)">登录</lay-dropdown-menu-item>
                <lay-dropdown-menu-item v-perm="'user_remove'" @click="toRemoveUserDom(row.id)">删除</lay-dropdown-menu-item>
              </lay-dropdown-menu>
            </template>
          </lay-dropdown>
        </template>

      </lay-table>
    </div>

    <!-- 外部组件 -->
    <add ref="addRef" title="新增用户" @refreshParent="userPage"></add>
    <edit ref="editRef" title="编辑用户" :id="params_id" @refreshParent="userPage"></edit>
    <detail ref="detailRef" title="用户详情" :id="params_id" ></detail>
    <reset-password ref="resetPasswordRef" :title="resetPasswordTitle" :id="params_id"></reset-password>

  </lay-container>
</template>
<script setup lang="ts">
import {ref, onMounted} from 'vue'
import {selectUserPage, removeUser, statusUser, simulateLogin, kickOutByToken,viewPassword} from '@/api/module/user'
import add from './add.vue'
import edit from './edit.vue'
import detail from './detail.vue'
import resetPassword from './resetPassword.vue'
import useFxwPage from '@/hooks/useFxwPage'
import useFxwForm from "@/hooks/useFxwForm";
import {useSimulateStore} from "@/store/simulate";
import {useBootStore} from "@/store/boot";
import {layer} from "@layui/layui-vue";

const {toReset} = useFxwForm()
const bootStore = useBootStore()
const simulateStore = useSimulateStore()

const fxwPage = useFxwPage();
const queryRef = ref();
const searchQuery = ref({
  username: '',
  nickName: '',
  status: '',
  pageNumber: 1,
  pageSize: 10,
})

const columns = ref([
  {title: '序号', width: '80px', key: '_index', customSlot: '_index'},
  // { title: '编号', width: '80px', key: 'id', fixed: 'left' },
  { title: '昵称', width: '120px', key: 'nickName' },
  { title: '用户名', width: '120px', key: 'username',},
  { title: '状态', width: '100px', key: 'status.desc',customSlot: 'status' },
  { title: '邮箱', width: '180px', key: 'email'},
  { title: '角色', customSlot: 'role', key: 'role' },
  { title: '生日', width: '120px', key: 'birthday' },
  { title: '操作', width: '100px', customSlot: 'operator', key: 'operator', fixed: 'right' }
])

onMounted(()=>{
  userPage();
})

// 用户列表
const userPage = function (cp:any = fxwPage.page){
  searchQuery.value.pageNumber = cp.current;
  searchQuery.value.pageSize = cp.limit;
  fxwPage.loading.value = true;
  selectUserPage(searchQuery.value).then(res=>{
    fxwPage.dataSource.value = res.data.records;

    fxwPage.loading.value = false;
    fxwPage.page.total = res.data.totalRow;
  })
}

// 新增用户
const addRef = ref();
const toAddUserDom = () => {
  addRef.value.changeVisible();
}
// 编辑用户
const editRef = ref();
const params_id = ref<number>()
const toEditUserDom = (id:number) => {
  params_id.value = id;
  editRef.value.changeVisible();
}

// 用户详情
const detailRef = ref();
const toDetailUserDom = (id:number) =>{
  params_id.value = id;
  detailRef.value.changeVisible();
}

// 删除用户
function toRemoveUserDom(id:number) {
  layer.confirm("确认删除该用户？",{
    btn: [
      {
        text:'确认',
        callback: (index:string) => {
          removeUser(id).then(res => {
            if (res.code == 200) {
              layer.close(index);
              userPage();
            }
          })
        }
      },
      {text:'取消', callback: (index:string) => {
          layer.close(index); }
      }
    ]
  })
}

// 切换状态
const statusUserBo = ref({
  id:0,
  status: ''
});
const changeStatus = function (row:any,status:string) {
  statusUserBo.value.id = row.id;
  statusUserBo.value.status = status;

  const statusBak = row.status.code;
  statusUser(statusUserBo.value).then(res => {
    if (res.code == 200) {
      userPage();
    }else {
      row.status.code = statusBak;
    }
  })
};

// 修改密码
const resetPasswordTitle = ref();
const resetPasswordRef = ref();
const toResetPasswordDom = function (row:any) {
  params_id.value = row.id;
  resetPasswordTitle.value = "修改密码 - "+ row.nickName + "（" + row.username +"）"
  resetPasswordRef.value.changeVisible();
};

// 查看密码
const toViewPasswordDom = function (row:any){
  viewPassword(row.id).then(res => {
    if (res.code === 200){
      layer.msg("用户【" + row.username + "】密码：" + res.data, { time: 1000 })
    }
  })
}

// 模拟登陆
const simulateLoginBo = ref({
  id: Number
});
const toSimulateLoginDom = function (row:any){
  if (bootStore.simulate) {
    layer.notify({
      title: "error",
      content: "当前窗口已处于模拟状态",
      icon:2
    })
    return false;
  }
  simulateLoginBo.value.id = row.id;
  simulateLogin(simulateLoginBo.value).then(res => {
    if (res.code !== 200){
      return false;
    }
    layer.open({
      title: false,
      type: "iframe",
      content: '/#/simulate',
      area: ["95%", "95%"],
      maxmin: false,
      shadeClose: false,
      success: (id:string) => {
        console.log(`成功:${id}`)
        bootStore.setSimulate(true,id)
        simulateStore.setToken(res.data);
      },
      end: (id:string) => {
        console.log(`销毁:${id}`)
        if (bootStore.simulate){
          kickOutByToken().then(res=>{
            if (res.code == 200) {
              simulateStore.delAll();
              bootStore.clearSimulate()
            }
          })
        }
      },
      min: (id:string) => {
        console.log(`最小化:${id}`)
        bootStore.clearSimulate()
      },
      full: (id:string) => {
        console.log(`最大化:${id}`)
        bootStore.setSimulate(true,id);
      }
    });
  })
}
</script>

<style scoped>
.user-box {
  height: calc(100vh - 110px);
  margin-top: 10px;
  box-sizing: border-box;
  overflow: hidden;
}

.top-search {
  margin-top: 10px;
  padding: 10px;
  height: 40px;
  border-radius: 4px;
  background-color: #fff;
}

.table-box {
  margin-top: 10px;
  padding: 10px;
  height: 700px;
  width: 100%;
  border-radius: 4px;
  box-sizing: border-box;
  background-color: #fff;
  .layui-tag{
    padding: 0 3px;
    margin: 0 2px;
  }
}

.search-input {
  display: inline-block;
  width: 98%;
  margin-right: 10px;
}

.isChecked {
  display: inline-block;
  background-color: #e8f1ff;
  color: red;
}
</style>